#include"RpcHeader.pb.h"
#include"RpcProvider.h"
#include"RpcApplication.h"
#include"zookeeperutil.h"
#include"ipAddressPort.h"
#include<google/protobuf/stubs/callback.h>



#include<functional>
std::unordered_map<std::string,struct ServiceInfo> RpcProvider::m_serviceMap{};
void RpcProvider::NotifyService(google::protobuf::Service *service)
{
    ServiceInfo service_info;

    
    const google::protobuf::ServiceDescriptor *pserviceDesc = service->GetDescriptor();
   
    std::string service_name = pserviceDesc->name();
 
    int methodCnt = pserviceDesc->method_count();

    std::cout << "service_name:" << service_name << std::endl;
    

    for (int i=0; i < methodCnt; ++i)
    {
       
        const google::protobuf::MethodDescriptor* pmethodDesc = pserviceDesc->method(i);
        std::string method_name = pmethodDesc->name();
        service_info.m_methodMap.emplace(method_name, pmethodDesc);

       
    }
    service_info.service = service;
    m_serviceMap.emplace(service_name, service_info);
}


void RpcProvider::Run()
{
   
    std::string ip = RpcApplication::getInstanceConfig().Load("rpcserverip");
    unsigned short port = atoi(RpcApplication::getInstanceConfig().Load("rpcserverport").c_str());
    IpAddressPort address(ip, port);


    m_Server.SetThreadNum(4);
    m_Server.SetIpAddressPort(address);
    /*
    ZKClient zkCli;
    zkCli.Start();
    // service_name为永久性节点    method_name为临时性节点
    for (auto &sp : m_serviceMap) 
    {
        // /service_name   /UserServiceRpc
        std::string service_path = "/" + sp.first;
        zkCli.Create(service_path.c_str(), nullptr, 0);
        for (auto &mp : sp.second.m_methodMap)
        {
            // /service_name/method_name   /UserServiceRpc/Login 存储当前这个rpc服务节点主机的ip和port
            std::string method_path = service_path + "/" + mp.first;
            char method_path_data[128] = {0};
            sprintf(method_path_data, "%s:%d", ip.c_str(), port);
            // ZOO_EPHEMERAL表示znode是一个临时性节点
            zkCli.Create(method_path.c_str(), method_path_data, strlen(method_path_data), ZOO_EPHEMERAL);
        }
    }

    */
    std::cout << "RpcProvider start service at ip:" << ip << " port:" << port << std::endl;

    // 启动网络服务
    m_Server.start();
   
}



// 已建立连接用户的读写事件回调 如果远程有一个rpc服务的调用请求，那么OnMessage方法就会响应
